package com.beeasy.hzbpm.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.beeasy.hzbpm.exception.BpmException;
import com.beeasy.hzbpm.util.Result;
import com.github.llyb120.nami.core.AopInvoke;
import com.github.llyb120.nami.core.RestException;
import com.github.llyb120.json.Obj;
import com.github.llyb120.json.Validate;
import com.github.llyb120.nami.server.Cookie;
import com.github.llyb120.nami.server.Request;
import com.github.llyb120.nami.server.Response;

import static com.beeasy.hzbpm.bean.MongoService.db;
import static com.github.llyb120.json.Json.o;
import static com.github.llyb120.json.Json.ooo;
import static com.github.llyb120.nami.core.Config.config;

public class Auth {

    private static ThreadLocal<String> uids = new ThreadLocal(){
        @Override
        protected String initialValue() {
            return "-1";
        }
    };

    public Object around(AopInvoke invoke, Cookie cookie, Obj headers, Request request, Response response) throws Exception {
        response.setHeader("expries", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        uids.set("-1");

        //login放开
        if(request.path.contains("/login/")){
            Obj user = getUser(request);
            if (user != null) {
                uids.set(user.s("uid"));
            }
        }
        else if(request.path.contains("/sync/")){
            String token = headers.ss("bpm-token");
            if(token.equals(config.var.ss("sync-token"))){
                uids.set("0");
            } else {
                return Result.error("没有登录");
            }
        }
        else if(!request.path.contains("download") && !request.path.contains("/support/")){
            Obj user = getUser(request);
            if (user == null) {
                return Result.error("没有登录");
            }
            uids.set(user.s("uid"));
        }
        try {
            Object ret = invoke.call();
            return ret;
        } catch (Exception e){
            e.printStackTrace();
            Throwable cause = e.getCause();
            if (cause != null) {
                if(cause instanceof Validate.Exception){
                    return Result.error(((Validate.Exception) cause).message);
                }
                if(cause instanceof BpmException){
                    return Result.error(((BpmException) cause).error);
                }
            }
        }
        return Result.error("错误请求");
    }

    private Obj getUser(Request request){
        String[] tokenNames = {"bpm-token", "Token", "token"};
        String token = null;
        for (String tokenName : tokenNames) {
            token = request.cookie.get(tokenName);
            if(!StrUtil.isBlank(token)){
                break;
            }
            token = request.headers.ss(tokenName);
            if(!StrUtil.isBlank(token)){
                break;
            }
            token = request.params.ss(tokenName);
            if(!token.isEmpty()){
                break;
            }
        }
        if (StrUtil.isBlank(token)) {
            return null;
        }
        token = URLUtil.decode(token);
        Obj user = ooo(db.getCollection("userToken").find(o("token", token).toBson()).first());
        return user.isEmpty() ? null : user;
    }

    public static String getUid(){
        return uids.get();
    }

    public static void setUid(String uid){
        uids.set(uid);
    }
}
